<template>
  <div id="addContestView">
    <a-card :bordered="false">
      <template #title>{{ isEdit ? "编辑竞赛" : "创建竞赛" }}</template>

      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="竞赛名称" name="title">
          <a-input
            v-model:value="formState.title"
            placeholder="请输入竞赛名称"
            allow-clear
          />
        </a-form-item>

        <a-form-item label="竞赛描述" name="description">
          <a-textarea
            v-model:value="formState.description"
            placeholder="请输入竞赛描述"
            :auto-size="{ minRows: 4, maxRows: 8 }"
            allow-clear
          />
        </a-form-item>

        <a-form-item label="开始时间" name="startTime">
          <a-date-picker
            v-model:value="formState.startTime"
            show-time
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
            style="width: 100%"
          />
        </a-form-item>

        <a-form-item label="竞赛时长" name="duration">
          <a-input-number
            v-model:value="formState.duration"
            :min="1"
            :max="1440"
            addon-after="分钟"
            placeholder="请输入竞赛时长"
            style="width: 200px"
          />
        </a-form-item>

        <a-form-item label="罚时" name="penalty">
          <a-input-number
            v-model:value="formState.penalty"
            :min="0"
            :max="120"
            addon-after="分钟"
            placeholder="请输入错误罚时"
            style="width: 200px"
          />
          <div class="form-item-tip">每次提交错误增加的罚时（分钟）</div>
        </a-form-item>

        <a-form-item label="竞赛类型" name="contestType">
          <a-radio-group v-model:value="formState.contestType">
            <a-radio :value="0">公开（无限制）</a-radio>
            <a-radio :value="1">密码保护</a-radio>
            <a-radio :value="2">私有（仅管理员可见）</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          v-if="formState.contestType === 1"
          label="竞赛密码"
          name="password"
        >
          <a-input-password
            v-model:value="formState.password"
            placeholder="请输入竞赛密码"
            allow-clear
            style="width: 300px"
          />
        </a-form-item>

        <a-form-item label="排名可见" name="visibleRank">
          <a-switch v-model:checked="formState.visibleRank" />
          <div class="form-item-tip">选中表示比赛期间可以看到排名</div>
        </a-form-item>

        <a-form-item label="竞赛题目" name="questionIds">
          <a-space direction="vertical" style="width: 100%">
            <a-button type="dashed" @click="showQuestionSelectModal" block>
              <template #icon><plus-outlined /></template>
              添加题目
            </a-button>
            <a-table
              :columns="selectedQuestionsColumns"
              :data-source="selectedQuestions"
              :pagination="false"
              size="small"
            >
              <template #bodyCell="{ column, record, index }">
                <template v-if="column.dataIndex === 'order'">
                  {{ index + 1 }}
                </template>
                <template v-if="column.dataIndex === 'title'">
                  {{ record.title }}
                </template>
                <template v-if="column.dataIndex === 'difficulty'">
                  <a-tag :color="getDifficultyColor(record.difficulty)">
                    {{ getDifficultyText(record.difficulty) }}
                  </a-tag>
                </template>
                <template v-if="column.dataIndex === 'action'">
                  <a-space>
                    <a-button
                      type="link"
                      size="small"
                      @click="moveQuestion(index, 'up')"
                      :disabled="index === 0"
                    >
                      上移
                    </a-button>
                    <a-button
                      type="link"
                      size="small"
                      @click="moveQuestion(index, 'down')"
                      :disabled="index === selectedQuestions.length - 1"
                    >
                      下移
                    </a-button>
                    <a-button
                      type="link"
                      danger
                      size="small"
                      @click="removeQuestion(index)"
                    >
                      删除
                    </a-button>
                  </a-space>
                </template>
              </template>
            </a-table>
          </a-space>
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
          <a-space>
            <a-button type="primary" @click="onSubmit">保存</a-button>
            <a-button @click="onCancel">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 题目选择弹窗 -->
    <a-modal
      v-model:visible="questionSelectModalVisible"
      title="选择题目"
      width="800px"
      @ok="handleSelectQuestions"
    >
      <a-table
        :columns="questionColumns"
        :data-source="questionList"
        :loading="questionsLoading"
        :pagination="{
          current: questionCurrent,
          pageSize: questionPageSize,
          total: questionTotal,
          showSizeChanger: true,
        }"
        :row-selection="{
          selectedRowKeys: selectedQuestionIds,
          onChange: onSelectChange,
        }"
        @change="handleQuestionTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'title'">
            {{ record.title }}
          </template>
          <template v-if="column.dataIndex === 'difficulty'">
            <a-tag :color="getDifficultyColor(record.difficulty)">
              {{ getDifficultyText(record.difficulty) }}
            </a-tag>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
/* eslint-disable */
import { ref, reactive, computed, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { message } from "ant-design-vue";
import { PlusOutlined } from "@ant-design/icons-vue";
import { ContestControllerService } from "../../../generated/services/ContestControllerService";
import { QuestionControllerService } from "../../../generated/services/QuestionControllerService";
import dayjs from "dayjs";

// 初始化路由
const route = useRoute();
const router = useRouter();
const isEdit = computed(() => route.params.id !== undefined);

// 表单相关
const formRef = ref();
const formState = reactive({
  id: undefined,
  title: "",
  description: "",
  startTime: "",
  duration: 120, // 默认120分钟
  penalty: 20, // 默认20分钟罚时
  contestType: 0, // 0-公开, 1-密码保护, 2-私有
  password: "",
  visibleRank: true,
  questionIds: [],
});

// 表单验证规则
const rules = {
  title: [{ required: true, message: "请输入竞赛名称", trigger: "blur" }],
  startTime: [{ required: true, message: "请选择开始时间", trigger: "change" }],
  duration: [{ required: true, message: "请输入竞赛时长", trigger: "change" }],
  penalty: [{ required: true, message: "请输入罚时", trigger: "change" }],
  password: [
    {
      required: true,
      message: "密码保护类型的竞赛需要设置密码",
      trigger: "blur",
      validator: (rule, value) => {
        if (formState.contestType === 1 && !value) {
          return Promise.reject(rule.message);
        }
        return Promise.resolve();
      },
    },
  ],
  questionIds: [
    {
      required: true,
      message: "请至少选择一个题目",
      trigger: "change",
      validator: (rule, value) => {
        if (!selectedQuestions.value || selectedQuestions.value.length === 0) {
          return Promise.reject(rule.message);
        }
        return Promise.resolve();
      },
    },
  ],
};

// 已选择的题目
const selectedQuestions = ref([]);
const selectedQuestionsColumns = [
  {
    title: "序号",
    dataIndex: "order",
    width: 80,
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "难度",
    dataIndex: "difficulty",
    width: 100,
  },
  {
    title: "操作",
    dataIndex: "action",
    width: 200,
  },
];

// 题目选择弹窗相关
const questionSelectModalVisible = ref(false);
const questionList = ref([]);
const questionsLoading = ref(false);
const questionCurrent = ref(1);
const questionPageSize = ref(10);
const questionTotal = ref(0);
const selectedQuestionIds = ref([]);
const questionColumns = [
  {
    title: "ID",
    dataIndex: "id",
    width: 80,
  },
  {
    title: "标题",
    dataIndex: "title",
  },
  {
    title: "难度",
    dataIndex: "difficulty",
    width: 100,
  },
];

// 加载竞赛详情
const loadContestDetail = async (id) => {
  try {
    const res = await ContestControllerService.getContestByIdUsingGet(id);
    if (res.code === 0) {
      const data = res.data;
      formState.id = data.id;
      formState.title = data.title;
      formState.description = data.description;
      formState.startTime = data.startTime ? dayjs(data.startTime) : null;
      formState.duration = data.duration;
      formState.penalty = data.penalty;
      formState.contestType = data.contestType;
      formState.password = data.password || "";
      formState.visibleRank = data.visibleRank;

      // 加载题目列表
      if (data.questionList && data.questionList.length > 0) {
        selectedQuestions.value = data.questionList.map((q) => ({
          ...q,
          key: q.id,
        }));
        selectedQuestionIds.value = data.questionList.map((q) => q.id);
      }
    } else {
      message.error("获取竞赛详情失败");
    }
  } catch (error) {
    console.error("获取竞赛详情异常", error);
    message.error("获取竞赛详情异常");
  }
};

// 加载题目列表
const loadQuestionList = async () => {
  try {
    questionsLoading.value = true;
    const res = await QuestionControllerService.listQuestionByPageUsingPost({
      current: questionCurrent.value,
      pageSize: questionPageSize.value,
      sortField: "createTime",
      sortOrder: "descend",
    });
    if (res.code === 0) {
      questionList.value = res.data.records.map((item) => ({
        ...item,
        key: item.id,
      }));
      questionTotal.value = res.data.total;
    } else {
      message.error("获取题目列表失败");
    }
  } catch (error) {
    console.error("获取题目列表异常", error);
    message.error("获取题目列表异常");
  } finally {
    questionsLoading.value = false;
  }
};

// 处理题目表格变化
const handleQuestionTableChange = (pagination) => {
  questionCurrent.value = pagination.current;
  questionPageSize.value = pagination.pageSize;
  loadQuestionList();
};

// 显示题目选择弹窗
const showQuestionSelectModal = () => {
  questionSelectModalVisible.value = true;
  loadQuestionList();
};

// 选择题目变化
const onSelectChange = (selectedRowKeys) => {
  selectedQuestionIds.value = selectedRowKeys;
};

// 确定选择题目
const handleSelectQuestions = () => {
  // 找出新选择的题目
  const newSelectedQuestions = [];

  selectedQuestionIds.value.forEach((id) => {
    // 检查是否已在已选题目中
    const existingIndex = selectedQuestions.value.findIndex((q) => q.id === id);
    if (existingIndex === -1) {
      // 不存在则添加
      const question = questionList.value.find((q) => q.id === id);
      if (question) {
        newSelectedQuestions.push({
          ...question,
          key: question.id,
        });
      }
    }
  });

  // 合并新选择的题目与已有题目
  selectedQuestions.value = [
    ...selectedQuestions.value,
    ...newSelectedQuestions,
  ];
  // 更新表单中的题目ID数组
  formState.questionIds = selectedQuestions.value.map((q) => q.id);

  questionSelectModalVisible.value = false;
};

// 移动题目顺序
const moveQuestion = (index, direction) => {
  if (direction === "up" && index > 0) {
    const temp = selectedQuestions.value[index];
    selectedQuestions.value[index] = selectedQuestions.value[index - 1];
    selectedQuestions.value[index - 1] = temp;
  } else if (
    direction === "down" &&
    index < selectedQuestions.value.length - 1
  ) {
    const temp = selectedQuestions.value[index];
    selectedQuestions.value[index] = selectedQuestions.value[index + 1];
    selectedQuestions.value[index + 1] = temp;
  }
  // 更新题目ID数组
  formState.questionIds = selectedQuestions.value.map((q) => q.id);
};

// 移除题目
const removeQuestion = (index) => {
  selectedQuestions.value.splice(index, 1);
  formState.questionIds = selectedQuestions.value.map((q) => q.id);
  selectedQuestionIds.value = formState.questionIds;
};

// 获取题目难度文本
const getDifficultyText = (difficulty) => {
  const difficultyMap = { 0: "简单", 1: "中等", 2: "困难" };
  return difficultyMap[difficulty] || "未知";
};

// 获取题目难度颜色
const getDifficultyColor = (difficulty) => {
  const colorMap = { 0: "green", 1: "orange", 2: "red" };
  return colorMap[difficulty] || "default";
};

// 提交表单
const onSubmit = async () => {
  try {
    await formRef.value.validate();

    // 准备请求数据
    const requestData = {
      ...formState,
      startTime: formState.startTime
        ? dayjs(formState.startTime).format("YYYY-MM-DD HH:mm:ss")
        : null,
    };

    // 根据是否编辑模式选择不同的API
    let res;
    if (isEdit.value) {
      res = await ContestControllerService.updateContestUsingPost(requestData);
    } else {
      res = await ContestControllerService.addContestUsingPost(requestData);
    }

    if (res.code === 0) {
      message.success(`${isEdit.value ? "编辑" : "创建"}竞赛成功`);
      router.push("/contests");
    } else {
      message.error(res.message || `${isEdit.value ? "编辑" : "创建"}竞赛失败`);
    }
  } catch (error) {
    console.error(`${isEdit.value ? "编辑" : "创建"}竞赛异常`, error);
    message.error(`请检查表单填写是否正确`);
  }
};

// 取消
const onCancel = () => {
  router.push("/contests");
};

// 生命周期钩子
onMounted(() => {
  if (isEdit.value && route.params.id) {
    loadContestDetail(route.params.id);
  }
});
</script>

<style scoped>
#addContestView {
  padding: 24px;
}

.form-item-tip {
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
  margin-top: 4px;
}
</style>
